package com.neiquan.backstage.meeting_order.web.action;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.neiquan.backstage.common.util.BackendErrorCode;
import com.neiquan.backstage.common.util.CommonResp;
import com.neiquan.backstage.common.util.ExtraSpringHibernateTemplate;
import com.neiquan.backstage.common.util.Paging;
import com.neiquan.backstage.common.util.Sessions;
import com.neiquan.backstage.meeting_order.MeetingOrderService;
import com.neiquan.backstage.meeting_room.MeetingRoomService;
import com.neiquan.backstage.pub.bsc.dao.po.AdminUser;
import com.neiquan.backstage.pub.bsc.dao.po.Entrepreneur;
import com.neiquan.backstage.pub.bsc.dao.po.MeetingOrder;
import com.neiquan.backstage.pub.bsc.dao.po.User;
import com.neiquan.backstage.resourec_manage.EntrepreneurService;

@Controller
@RequestMapping(value = "meetingOrderAction", produces = { "text/json;charset=UTF-8" })
public class MeetingOrderAction {
	private static Class<?> poc = MeetingOrder.class;
	@Autowired
	private ExtraSpringHibernateTemplate extraSpringHibernateTemplate;
	@Autowired
	private MeetingOrderService meetingOrderService;
	@Autowired
	private EntrepreneurService entrepreneurService;
	@Autowired
	private MeetingRoomService meetingRoomService;
	
	@ResponseBody
	@RequestMapping("list")
	public String list(int pageIndex, int pageSize, HttpSession session) throws ParseException {
		User user = (User) Sessions.getLoginedUser(session);
		Integer memberId = user.getMemberId();
		Date date = new Date();
		long currentTimeMillis = System.currentTimeMillis();
		date.setTime(currentTimeMillis);
		SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
		String format = simple.format(date);
		Date parse = simple.parse(format);
		Calendar cal = Calendar.getInstance();
		cal.setTime(parse);
		long timeInMillis = cal.getTimeInMillis();
		List<MeetingOrder> listM = (List<MeetingOrder>) extraSpringHibernateTemplate.getHibernateTemplate()
				.find("From MeetingOrder where memberId=? and dtCreat>?", memberId,timeInMillis);
		if(listM.size()<=0){
			return CommonResp.buildSuccessResp().toJsonString();
		}
		return CommonResp.buildSuccessResp(fillTime(listM)).toJsonString();
	}
	
	private List<Object> fillTime(List<MeetingOrder> list) {
		List<Object> resultList = new ArrayList<>();
		for (MeetingOrder mo : list) {
			String time = "";
			Map<String, Object> mapM = new HashMap<>();
			mapM.put("meetingRoomName", mo.getMeetingRoomName());
			mapM.put("status", mo.getStatus());
			mapM.put("entrepreneurName", mo.getEntrepreneurName());
			mapM.put("name", mo.getName());
			mapM.put("phone", mo.getPhone());
			mapM.put("meetingOrderId", mo.getMeetingOrderId());
			String times = mo.getTimes();
			if (times != null && !times.equals("")) {
				String[] split = times.split(",");
				String[] split3 = split[0].split("-");
				if (split3.length > 3) {
					time = split3[0] + "-" + split3[1] + "-" + split3[2] + " ";
					int[] array = new int[split.length];
					for (int i = 0; i < split.length; i++) {
						String[] split2 = split[i].split("-");
						String b = split2[3];
						array[i] = Integer.parseInt(b);
					}
					Arrays.sort(array);
					int mina = array[0];
					int maxa = array[split.length - 1];
					time += mina + "--" + maxa;
					mapM.put("time", time);
				}
			}
			resultList.add(mapM);
		}
		return resultList;
	}
	
	/**
	 * meetingRoom通过名字查询
	 * @param meetingRoomName
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping("findByMRNameAll")
	public String findByMRNameAll(String meetingRoomName,HttpSession session) {
		User user = (User) Sessions.getLoginedUser(session);
		Integer memberId = user.getMemberId();
		List<MeetingOrder> list=(List<MeetingOrder>) extraSpringHibernateTemplate.getHibernateTemplate().find("From MeetingOrder where memberId=? and meetingRoomName=?", memberId,meetingRoomName);
		return CommonResp.buildSuccessResp(list).toJsonString();
	}
	
	@ResponseBody
	@RequestMapping("findByAddressAll")
	public String findByAddressAll(Integer meetingRoomId,HttpSession session) {
		User user = (User) Sessions.getLoginedUser(session);
		Integer memberId = user.getMemberId();
		List<MeetingOrder> list=(List<MeetingOrder>) extraSpringHibernateTemplate.getHibernateTemplate().find("From MeetingOrder where memberId=? and meetingRoomId=?", 1,meetingRoomId);
		return CommonResp.buildSuccessResp(list).toJsonString();
	}

	@ResponseBody
	@RequestMapping(value = "queryDetail")
	public String queryDetail(Integer id) {
		List<MeetingOrder> list = new ArrayList<>();
		list.add(meetingOrderService.queryById(id));
		return CommonResp.buildSuccessResp(fillTime(list).get(0)).toJsonString();
	}

	@ResponseBody
	@RequestMapping(value = "remove")
	public String remove(Integer id) {
		MeetingOrder toDelete = meetingOrderService.queryById(id);
		if (toDelete == null) {
			return CommonResp.buildErrorResp(BackendErrorCode.not_exist).toJsonString();
		}
		extraSpringHibernateTemplate.getHibernateTemplate().delete(toDelete);
		return CommonResp.buildSuccessResp().toJsonString();
	}

	@ResponseBody
	@RequestMapping(value = "pass")
	public String pass(Integer id) {
		MeetingOrder toUpdate = meetingOrderService.queryById(id);
		if (toUpdate == null) {
			return CommonResp.buildErrorResp(BackendErrorCode.not_exist).toJsonString();
		}
		if (toUpdate.getStatus() != MeetingOrder.status_wait) {
			return CommonResp.buildErrorResp(BackendErrorCode.status_error).toJsonString();
		}
		toUpdate.setStatus(MeetingOrder.status_pass);
		extraSpringHibernateTemplate.getHibernateTemplate().update(toUpdate);
		return CommonResp.buildSuccessResp().toJsonString();
	}

	@ResponseBody
	@RequestMapping(value = "reject")
	public String reject(Integer id) {
		MeetingOrder toUpdate = meetingOrderService.queryById(id);
		if (toUpdate == null) {
			return CommonResp.buildErrorResp(BackendErrorCode.not_exist).toJsonString();
		}
		if (toUpdate.getStatus() != MeetingOrder.status_wait) {
			return CommonResp.buildErrorResp(BackendErrorCode.status_error).toJsonString();
		}
		toUpdate.setStatus(MeetingOrder.status_reject);
		extraSpringHibernateTemplate.getHibernateTemplate().update(toUpdate);
		return CommonResp.buildSuccessResp().toJsonString();
	}

	@ResponseBody
	@RequestMapping(value = "search")
	public String search(String name, String entrepreneurName, HttpSession session) {
		User user = (User) Sessions.getLoginedUser(session);
		Integer memberId = user.getMemberId();
		List<Criterion> criterions = new ArrayList<>();
		criterions.add(Restrictions.eq("memberId", user.getMemberId()));
		if (StringUtils.isNoneBlank(name)) {
			criterions.add(Restrictions.like("name", "%" + name + "%"));
		}
		if (StringUtils.isNoneBlank(entrepreneurName)) {
			criterions.add(Restrictions.like("entrepreneurName", "%" + entrepreneurName + "%"));
		}
		Criterion criterion = Restrictions.and(criterions.toArray(new Criterion[] {}));
		DetachedCriteria queryListCriteria = ExtraSpringHibernateTemplate.C.build(poc, Order.desc("meetingOrderId"), criterion);
		DetachedCriteria queryCountCriteria = ExtraSpringHibernateTemplate.C.buildRowCount(poc, criterion);
		Paging<?> paging = extraSpringHibernateTemplate.findPageByCriteria(queryListCriteria, queryCountCriteria, 0, Integer.MAX_VALUE);
		return CommonResp.buildSuccessResp(paging).toJsonString();
	}

	@ResponseBody
	@RequestMapping(value = "add")
	public String add(Integer meetingRoomId, @RequestParam("orderTimes[]")String[] orderTimes, HttpSession session) throws ParseException {
		User user = (User) Sessions.getLoginedUser(session);
		String phone = user.getPhone();
		String name = user.getName();
		Integer userId = user.getUserId();
		Integer memberId = user.getMemberId();
		String uniqueId = user.getEntrepreneurUniqueId();
		Entrepreneur entityE = entrepreneurService.queryByUniqueId(uniqueId, memberId);
		Integer entrepreneurId = entityE.getEntrepreneurId();
		MeetingOrder toSave = new MeetingOrder();
		toSave.setMemberId(memberId);
		String times="";
		for (String str : orderTimes) {
			if (StringUtils.isBlank(str)) {
				continue;
			}
			toSave.setStatus(MeetingOrder.status_wait);
			String[] strs = str.split(",");
			times += strs[0] + "-" + Integer.parseInt(strs[1]) + ",";
		}
		if (StringUtils.isBlank(times)) {
			return CommonResp.buildErrorResp("请选择时间").toJsonString();
		}
		times=times.substring(0, times.length()-1);
		toSave.setTimes(times);
		toSave.setEntrepreneurId(entrepreneurId);
		toSave.setApplyType(MeetingOrder.apply_meeting);
		toSave.setEntrepreneurName(entrepreneurService.queryById(entrepreneurId).getName());
		toSave.setName(name);
		toSave.setDtCreat(System.currentTimeMillis());
		toSave.setMeetingRoomId(meetingRoomId);
		toSave.setMeetingRoomName(meetingRoomService.queryById(meetingRoomId).getName());
		toSave.setPhone(phone);
		toSave.setUserId(userId);
		extraSpringHibernateTemplate.getHibernateTemplate().save(toSave);
		return CommonResp.buildSuccessResp().toJsonString();
	}

	
}
